import Vue from "vue";
import Vuex from "vuex";
import union from "./module/union";
import orderMeal from "./module/orderMeal";
import utils from "@/common/utils";
Vue.use(Vuex);

const store = new Vuex.Store({
  state: {
    personalnews: "",
    sub_order_msg: "",
    community_list: "",
    stores: {},
    images: {},
    share_setting: {},
    cat_list: "", //分类列表内容,
    userInfo: false,
    controls: [],
    platform_appid: "",
    // 购物车数量
    cartNum: 0,
    noLoginTabarPath: "",
    routeType: "",
    // 领取优惠券弹窗是否显示
    showGetCoupon: false,
    // 领取的优惠券
    gettedCoupon: {},
    shenheStatus: "-1",
    shenheAliStatus: "",
    change_shop: "",
    is_one_store: false, // 是否为单店铺模式
    one_store_switch_store: false, // 是否切换门店
    go_cat_id: "", // 分类id
    store_id: "",
    locationData: "",
    one_store_hide_apply: "0",
    storeMdData: "",
    indexSearchHeight: 0,
    copyright: ""
  },
  mutations: {
    setCopyright(state, data) {
      state.copyright = data;
      uni.setStorageSync("copyright", data);
    },
    setIndexSearchHeight(state, data) {
      uni.setStorageSync("indexSearchHeight", data);
      state.indexSearchHeight = data;
    },
    setStoreMdData(state, data) {
      state.storeMdData = data;
      uni.setStorageSync("storeMdData", data);
    },
    setStoreId(state, data) {
      uni.setStorageSync("store_id", data);
      state.store_id = data;
    },
    setGoCatId(state, data) {
      uni.setStorageSync("go_cat_id", data);
      state.go_cat_id = data;
    },
    setShenheStatus(state, data) {
      uni.setStorageSync("shenheStatus", data);
      state.shenheStatus = data;
    },

    setchange_shop(state, data) {
      uni.setStorageSync("change_shop", data);
      state.change_shop = data;
    },

    setShenheAliStatus(state, data) {
      uni.setStorageSync("shenheAliStatus", data);
      state.shenheAliStatus = data;
    },
    setUserInfo(state, data) {
      state.userInfo = data;
    },
    setStores(state, data) {
      state.stores = data;
    },
    setImages(state, data) {
      state.images = data;
    },
    setShareSetting(state, data) {
      state.share_setting = data;
    },
    setOneStoreSwitchStore(state, data) {
      state.one_store_switch_store = data;
    },
    setControls: (state, data) => {
      state.controls = data;
    },
    setPlatformAppid: (state, data) => {
      state.platform_appid = data;
    },
    //设置购物车数量
    setCartNum(state, { list, mch_list }) {
      let num = 0;
      // 计算自营购物车件数
      list.length
        ? list.forEach((item) => {
            num += item.num;
          })
        : "";
      // 计算入驻商家商品件数
      if (mch_list) {
        mch_list.forEach((item) => {
          item.list.length
            ? item.list.forEach((item1) => {
                num += item1.num;
              })
            : "";
        });
      }
      uni.setStorageSync("cartNum", num);
      state.cartNum = num;
    },
    setNoLoginTabarPath: (state, data) => {
      state.noLoginTabarPath = data;
    },
    setRouteType: (state, data) => {
      state.routeType = data;
    },
    setLocation(state, data) {
      state.locationData = data;
      uni.setStorageSync("locationData", data);
    },
    setOneStoreHideApply(state, data) {
      state.one_store_hide_apply = data;
    }
  },
  getters: {
    copyright(state) {
      return state.copyright || uni.getStorageSync("copyright");
    },
    userInfo(state) {
      return state.userInfo || uni.getStorageSync("userInfo");
    },
    getIndexSearchHeight(state) {
      if (state.indexSearchHeight) {
        return state.indexSearchHeight;
      } else {
        return uni.getStorageSync("indexSearchHeight");
      }
    },
    storeMdData(state) {
      return state.storeMdData || uni.getStorageSync("storeMdData");
    },
    // 定位信息
    locationData(state) {
      return uni.getStorageSync("locationData") || state.locationData;
    },
    getStoreId(state) {
      if (state.store_id) {
        return state.store_id;
      } else {
        return uni.getStorageSync("go_cat_id");
      }
    },
    getGoCatId(state) {
      if (state.go_cat_id) {
        return state.go_cat_id;
      } else {
        return uni.getStorageSync("go_cat_id");
      }
    },
    shenheStatus(state) {
      if (state.shenheStatus.length) {
        return state.shenheStatus;
      } else {
        return uni.getStorageSync("shenheStatus");
      }
    },

    change_shop(state) {
      if (state.change_shop.length) {
        return state.change_shop;
      } else {
        return uni.getStorageSync("change_shop");
      }
    },

    shenheAliStatus(state) {
      if (state.shenheAliStatus.length) {
        return state.shenheAliStatus;
      } else {
        return uni.getStorageSync("shenheAliStatus");
      }
    },
    has_is_one_store: (state) => {
      return state.is_one_store;
    },
    stores: (state) => {
      return state.stores;
    },
    images: (state) => {
      return state.images;
    },
    share_setting: (state) => {
      return state.share_setting;
    },
    one_store_switch_store: (state) => {
      return state.one_store_switch_store;
    },
    controls: (state) => {
      return state.controls;
    },
    platform_appid: (state) => {
      return state.platform_appid;
    },
    cartNum: (state) => {
      return state.cartNum || uni.getStorageSync("cartNum") || 0;
    },
    noLoginTabarPath: (state) => {
      return state.noLoginTabarPath;
    },
    routeType: (state) => {
      return state.routeType;
    },
    showGetCoupon: (state) => {
      return state.showGetCoupon;
    },
    gettedCoupon: (state) => {
      return state.gettedCoupon;
    },
    one_store_hide_apply: (state) => {
      return state.one_store_hide_apply;
    }
  },
  actions: {
    getLocation(t) {
      // #ifndef APP-PLUS
      // #endif
      // 获取经纬度
      // 获取定位逻辑如下：
      // 1.判断是否拒绝过定位。不再弹起授权框，改为指导用户授权（app要求）
      // 1.1 查询是否已打开授权，没有提示用户打开授权，如果用户已打开正常获取定位信息，需清除拒绝定位操作。用于下次调用定位获取最新位置。
      // 2.未定位过 || 定位超时  重新更新当前位置
      // 3.默认返回定位为空，防止报错

      
      if((uni.getStorageSync('platform') || uni.getSystemInfoSync().platform) == 'android'){
      return new Promise((resolve, reject) => {
        utils.showModal(
          "定位权限使用说明",
          "当前功能用于计算距离",
          true,
          () => {
            let locationData = t.getters["locationData"];
            let time = new Date().getTime();
            let noLocation = uni.getStorageSync("noLocation");
            // 用户拒绝过授权定位
            if (noLocation) {
              // 判断用户是否已打开定位权限  未打开引导用户去打开
              uni.getSetting({
                success: ({ authSetting }) => {
                  if (authSetting["scope.userLocation"]) {
                    uni.getLocation({
                      type: "gcj02",
                      success: (res) => {
                        t.commit("setLocation", {
                          ...res,
                          currentDate: time
                        });
                        resolve({
                          ...res,
                          currentDate: time
                        });
                      },
                      fail: (err) => {
                        if (err.errMsg === "getLocation:fail auth deny") {
                          uni.setStorageSync("noLocation", true);
                        }
                        t.commit("setLocation", {
                          longitude: "",
                          latitude: "",
                          currentDate: time
                        });

                        resolve({
                          longitude: "",
                          latitude: "",
                          currentDate: time
                        });
                      }
                    });
                    uni.removeStorageSync("noLocation");
                  } else {
                    uni.showModal({
                      title: "提示",
                      content: "当前功能需授权定位信息！",
                      showCancel: true,
                      cancelText: "关闭",
                      confirmText: "去打开",
                      success: (result) => {
                        if (result.confirm) {
                          uni.openSetting();
                        }
                        resolve({
                          longitude: "",
                          latitude: "",
                          currentDate: time
                        });
                      },
                      fail: () => {},
                      complete: () => {}
                    });
                  }
                }
              });
            }
            // 未定位过 || 定位已超过1分钟
            else if (
              !locationData ||
              (locationData.currentDate < time - 1 * 60 * 1000 &&
                !locationData.isSwitch)
            ) {
              uni.getLocation({
                type: "gcj02",
                success: (res) => {
                  t.commit("setLocation", {
                    ...res,
                    currentDate: time
                  });
                  resolve({
                    ...res,
                    currentDate: time
                  });
                },
                fail: (err) => {
                  if (err.errMsg === "getLocation:fail auth deny") {
                    uni.setStorageSync("noLocation", true);
                  }
                  t.commit("setLocation", {
                    longitude: "",
                    latitude: "",
                    currentDate: time
                  });

                  resolve({
                    longitude: "",
                    latitude: "",
                    currentDate: time
                  });
                }
              });
            } else {
              resolve(locationData);
            }
          },
          () => {
            resolve({
              longitude: "",
              latitude: "",
              time: new Date().getTime()
            });
          }
        );
      });
      }
      return new Promise((resolve, reject) => {
        let locationData = t.getters["locationData"];
        let time = new Date().getTime();
        let noLocation = uni.getStorageSync("noLocation");
        // 用户拒绝过授权定位
        if (noLocation) {
          // 判断用户是否已打开定位权限  未打开引导用户去打开
          uni.getSetting({
            success: ({ authSetting }) => {
              if (authSetting["scope.userLocation"]) {
                uni.getLocation({
                  type: "gcj02",
                  success: (res) => {
                    t.commit("setLocation", {
                      ...res,
                      currentDate: time
                    });
                    resolve({
                      ...res,
                      currentDate: time
                    });
                  },
                  fail: (err) => {
                    if (err.errMsg === "getLocation:fail auth deny") {
                      uni.setStorageSync("noLocation", true);
                    }
                    t.commit("setLocation", {
                      longitude: "",
                      latitude: "",
                      currentDate: time
                    });

                    resolve({
                      longitude: "",
                      latitude: "",
                      currentDate: time
                    });
                  }
                });
                uni.removeStorageSync("noLocation");
              } else {
                uni.showModal({
                  title: "提示",
                  content: "当前功能需授权定位信息！",
                  showCancel: true,
                  cancelText: "关闭",
                  confirmText: "去打开",
                  success: (result) => {
                    if (result.confirm) {
                      uni.openSetting();
                    }
                    resolve({
                      longitude: "",
                      latitude: "",
                      currentDate: time
                    });
                  },
                  fail: () => {},
                  complete: () => {}
                });
              }
            }
          });
        }
        // 未定位过 || 定位已超过1分钟
        else if (
          !locationData ||
          (locationData.currentDate < time - 1 * 60 * 1000 &&
            !locationData.isSwitch)
        ) {
          uni.getLocation({
            type: "gcj02",
            success: (res) => {
              t.commit("setLocation", {
                ...res,
                currentDate: time
              });
              resolve({
                ...res,
                currentDate: time
              });
            },
            fail: (err) => {
              if (err.errMsg === "getLocation:fail auth deny") {
                uni.setStorageSync("noLocation", true);
              }
              t.commit("setLocation", {
                longitude: "",
                latitude: "",
                currentDate: time
              });

              resolve({
                longitude: "",
                latitude: "",
                currentDate: time
              });
            }
          });
        } else {
          resolve(locationData);
        }
      });
    }
  },
  modules: {
    union,
    orderMeal
  }
});
export default store;
